import { Component, EventEmitter, Input, OnInit, Output, OnDestroy } from '@angular/core';

import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap, takeUntil } from 'rxjs/operators';

import { HttpRequestService } from '../../../core/services/http-request.service';
import { BaseDirective } from '../../../core/models/base-directive.model';

/**
 * Goes to remote server by following the provided url to check if the input value is duplicate.
 * checkCompleted event fires with true means the input is duplicate. False means NOT.
 */
@Component({
    selector: 'op-async-requestor',
    template: ''
})
export class AsyncRequestorComponent extends BaseDirective implements OnInit, OnDestroy {
    @Output() requestCompleted: EventEmitter<any> = new EventEmitter();
    @Input() valueToCheck: Subject<string>;
    @Input() url: string;
    @Input() debounceTime: number = 1000;

    constructor() {
        super();
    }

    ngOnInit(): void {
        this.valueToCheck.pipe(debounceTime(this.debounceTime)).pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => {
            let param = {
                value: data
            }

            this.httpRequestService.get<any>(this.url, param).subscribe(data => this.requestCompleted.emit(data.result));

            // this.httpRequestService.getWithoutBaseUrl<any>('/assets/user-demo-data/user-list.json').subscribe(users => {
            //     users.result.every(user => {
            //         let isValueMatched = user.loginName === data;
            //         this.checkCompleted.emit(isValueMatched);

            //         // When you are dealing with backend service instead of the json file you don't need the return statement.
            //         return !isValueMatched;
            //     });
            // })
        });
    }

    ngOnDestroy(): void {
        super.ngOnDestroy();
    }
}